<template>
<div id="app"  >
  <div class="button" @click="butLog" >输出</div>
  <div ref="container" style="width: 100%; height: 500px;">
    
  </div>

</div>
</template>

<script>
import * as THREE from 'three';
// 引入OrbitControls
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
export default {
  name: 'EarthThree',
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      earthMesh: null,
      controls: null,
      animationId: null,
    };
  },
  mounted() {
    this.initThree();
    this.animate();
    window.addEventListener('resize', this.onWindowResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onWindowResize);
    cancelAnimationFrame(this.animationId);
    if (this.renderer) {
      this.renderer.dispose();
      this.renderer.forceContextLoss();
      this.renderer.context = null;
      this.renderer.domElement = null;
      this.renderer = null;
    }
    if (this.controls) {
      this.controls.dispose();
      this.controls = null;
    }
  },
  methods: {
    butLog(){
      const direction = new THREE.Vector3();
      console.log(1111,this.camera.position,this.camera.getWorldDirection(direction));
      // this.camera.position.set(-0.3948866593660801, 1.233375150733576, -1.2889187262799264)
      const earthRadius = 1; // 你的地球半径
      const lat = 39.9;      // 纬度，北京示例
      const lng = 116.4;     // 经度，北京示例
      const cubeSize = 0.05; // 正方体大小

      const cube = createCubeAtLatLng(lat, lng, cubeSize, earthRadius);
      this.scene.add(cube);
    },
    initThree() {
      // 创建场景
      this.scene = new THREE.Scene();

      // 创建相机
      const width = this.$refs.container.clientWidth;
      const height = this.$refs.container.clientHeight;
      this.camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000);
      this.camera.position.z = 3;
      


      // 创建渲染器
      this.renderer = new THREE.WebGLRenderer({ antialias: true });
      this.renderer.setSize(width, height);
      this.$refs.container.appendChild(this.renderer.domElement);

      // 添加光源
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
      this.scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
      directionalLight.position.set(5, 3, 5);
      this.scene.add(directionalLight);

      // 创建地球球体
      const geometry = new THREE.SphereGeometry(1, 128,128);

      // 加载纹理
      const textureLoader = new THREE.TextureLoader();
      const earthTexture = textureLoader.load('/image/earthmap1k.jpg'); // 确保路径正确
      // earthTexture.wrapS = THREE.RepeatWrapping;
      // earthTexture.wrapT = THREE.RepeatWrapping;
      // // 根据球体大小调整重复次数，radius越大，repeat越大
      // const repeatCount = 1000; // 这里可以根据半径调整，比如和半径成比例
      // earthTexture.repeat.set(repeatCount, repeatCount);

      const material = new THREE.MeshPhongMaterial({
        map: earthTexture,
      });

      this.earthMesh = new THREE.Mesh(geometry, material);
      this.scene.add(this.earthMesh);


      // 初始化OrbitControls
      this.controls = new OrbitControls(this.camera, this.renderer.domElement);
      // 设置控制参数
      this.controls.enableDamping = true; // 启用阻尼（惯性）
      this.controls.dampingFactor = 0.05;
      this.controls.enableZoom = true; // 允许缩放
      this.controls.minDistance = 1.5; // 最小缩放距离
      this.controls.maxDistance = 5000;   // 最大缩放距离
      this.controls.enablePan = true; // 禁止平移
    },
    animate() {
      this.animationId = requestAnimationFrame(this.animate);

      // 更新控制器
      if (this.controls) {
        this.controls.update();
      }
      // // 旋转地球
      // if (this.earthMesh) {
      //   this.earthMesh.rotation.y += 0.001;
      // }

      this.renderer.render(this.scene, this.camera);
    },
    onWindowResize() {
      const width = this.$refs.container.clientWidth;
      const height = this.$refs.container.clientHeight;

      this.camera.aspect = width / height;
      this.camera.updateProjectionMatrix();

      this.renderer.setSize(width, height);
    },
  },
};
function latLngToVector3(lat, lng, radius) {
  const phi = (90 - lat) * (Math.PI / 180);
  const theta = (lng + 180) * (Math.PI / 180);

  const x = -radius * Math.sin(phi) * Math.cos(theta);
  const y = radius * Math.cos(phi);
  const z = radius * Math.sin(phi) * Math.sin(theta);

  return new THREE.Vector3(x, y, z);
}
function createCubeAtLatLng(lat, lng, size, radius) {
  const position = latLngToVector3(lat, lng, radius);

  // 创建正方体几何体
  const geometry = new THREE.BoxGeometry(size, size, size);
  const material = new THREE.MeshStandardMaterial({ color: 0xff0000 });
  const cube = new THREE.Mesh(geometry, material);

  // 设置位置
  cube.position.copy(position);

  // 让正方体“站立”在地球表面，调整朝向
  // 计算从地球中心指向该点的法线向量（单位向量）
  const normal = position.clone().normalize();

  // 计算旋转四元数，使正方体的“上”方向与法线方向一致
  const up = new THREE.Vector3(0, 1, 0); // 正方体默认“上”方向
  const quaternion = new THREE.Quaternion().setFromUnitVectors(up, normal);
  cube.quaternion.copy(quaternion);

  return cube;
}

</script>

<style>
#app {
  width: 100%;
  height: 100%;
  /* font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px; */
}
</style>
